<!-- 流程模型管理 -->
<template>
  <div>
    <!-- 查询条件 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="模型名称">
        <el-input v-model="searchForm.name" placeholder="请输入模型名称" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchList">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
      <el-form-item>
        <!-- <el-button type="success" @click="openUploadDialog">上传模型</el-button>
        <el-button type="danger" :disabled="!multipleSelection.length" @click="batchDelete">批量删除</el-button> -->
      </el-form-item>
    </el-form>

    <!-- 列表 -->
    <div class="card-list">
      <el-row :gutter="20">
        <el-col :span="6" v-for="item in tableData" :key="item.fileName">
          <el-card class="process-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>{{ item.processName }}</span>
                <div class="card-actions">
                  <el-button type="primary" link @click="previewModel(item)">预览</el-button>
                  <el-button type="danger" link @click="deleteRow(item)">删除</el-button>
                </div>
              </div>
            </template>
            <div class="card-content">
              <el-icon><Document /></el-icon>
              <span class="file-name">{{ item.fileName }}</span>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 上传模型弹窗 -->
    <el-dialog v-model="uploadDialogVisible" title="上传流程模型">
      <el-form :model="uploadForm" :rules="rules" ref="uploadFormRef" label-width="100px">
        <el-form-item label="模型名称" prop="name">
          <el-input v-model="uploadForm.name" />
        </el-form-item>
        <el-form-item label="模型文件" prop="file">
          <el-upload
            class="upload-demo"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :on-exceed="handleExceed"
            :limit="1"
            accept=".xml"
            :show-file-list="true"
            :file-list="fileList"
            :before-remove="beforeFileRemove"
          >
            <template #trigger>
              <el-button type="primary">选择 BPMN 2.0 XML 文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                请上传符合 BPMN 2.0 规范的 XML 文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="uploadModel">确定</el-button>
      </template>
    </el-dialog>

    <!-- 预览模型弹窗 -->
    <el-dialog v-model="previewDialogVisible" title="预览流程模型" width="80%">
      <div class="preview-container">
        <div id="canvas" class="canvas"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import BpmnViewer from 'bpmn-js/lib/Viewer'
import { Document } from '@element-plus/icons-vue'

export default {
  name: 'ProcessModel',
  components: {
    Document
  },
  data() {
    return {
      searchForm: {
        name: ''
      },
      tableData: [], // 模型列表数据
      multipleSelection: [], // 多选
      uploadDialogVisible: false,
      previewDialogVisible: false,
      uploadForm: {
        name: '',
        file: null
      },
      fileList: [], // 文件列表
      selectedFile: null, // 选中的文件
      isFileValid: false, // 文件是否验证通过
      bpmnViewer: null, // BPMN 查看器实例
      rules: {
        name: [
          { required: true, message: '请输入模型名称', trigger: 'blur' }
        ],
        file: [
          { required: true, message: '请上传模型文件', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    // 查询
    fetchList() {
      // TODO: 调用接口获取数据
      // this.tableData = await api.getModelList(this.searchForm)
      this.$get('/getAllProcessFiles',{
        name : this.searchForm.name
      }).then(res =>{
        if(res.code === 200){
          this.tableData = res.data
        }else{
          ElMessage.error('获取模型列表失败')
        }
      }).catch(err =>{
        console.log(err)
      })
    },
    // 重置
    resetSearch() {
      this.searchForm = { name: '' }
      this.fetchList()
    },
    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 上传
    openUploadDialog() {
      this.uploadDialogVisible = true
      this.uploadForm = { 
        name: '', 
        file: null 
      }
      this.resetFile()
    },
    async uploadModel() {
      if (!this.selectedFile || !this.isFileValid) {
        ElMessage.warning('请先选择并验证通过 BPMN 2.0 XML 文件')
        return
      }

      try {
        await this.$refs.uploadFormRef.validate()
      } catch (error) {
        return
      }

      // 创建 FormData 对象
      const formData = new FormData()
      formData.append('file', this.selectedFile)
      formData.append('name', this.uploadForm.name)

      try {
        // TODO: 调用上传接口
        // const response = await api.uploadModel(formData)
        ElMessage.success('上传成功')
        this.uploadDialogVisible = false
        this.fetchList()
      } catch (error) {
        ElMessage.error('上传失败：' + error.message)
      }
    },
    // 预览
    async previewModel(row) {
      this.previewDialogVisible = true
      this.$get('/getProcessFileXml',{
        fileName : row.fileName
      }).then(res =>{
        if(res.code === 200){
          this.initBpmnModeler(res.data)
        }else{
          ElMessage.error('获取模型文件失败')
        }
      }).catch(err =>{
        console.log(err)
      })
    },
    // 初始化 BPMN 查看器
    initBpmnModeler(xml) {
      if (this.bpmnViewer) {
        this.bpmnViewer.destroy()
      }

      this.bpmnViewer = new BpmnViewer({
        container: '#canvas',
        keyboard: {
          bindTo: window
        }
      })

      this.bpmnViewer.importXML(xml).then(() => {
        const canvas = this.bpmnViewer.get('canvas')
        canvas.zoom('fit-viewport')
      }).catch(err => {
        ElMessage.error('模型加载失败：' + err.message)
      })
    },
    // 批量删除
    batchDelete() {
      ElMessageBox.confirm('确定要批量删除选中的模型吗？', '提示', {
        type: 'warning'
      }).then(() => {
        // TODO: 调用批量删除接口
        ElMessage.success('删除成功')
        this.fetchList()
      })
    },
    // 单个删除
    deleteRow(row) {
      ElMessageBox.confirm('确定要删除该模型吗？', '提示', {
        type: 'warning'
      }).then(() => {
        // TODO: 调用删除接口
        ElMessage.success('删除成功')
        this.fetchList()
      })
    },
    // 文件处理相关方法
    handleExceed(files) {
      this.resetFile()
      this.validateAndSetFile(files[0])
    },
    handleFileChange(file) {
      if (!file) return
      this.validateAndSetFile(file)
    },
    validateAndSetFile(file) {
      this.selectedFile = file.raw
      this.uploadForm.file = file.raw
      this.fileList = [{
        name: file.name,
        raw: file.raw,
        size: file.size,
        status: 'ready'
      }]
      
      this.isFileValid = false
      
      // 检查文件类型
      const isXML = file.raw.type === 'application/xml' || file.raw.name.endsWith('.xml')
      if (!isXML) {
        ElMessage.error('只能上传 XML 文件!')
        this.resetFile()
        return
      }

      // 检查文件大小（限制为 10MB）
      const isLt10M = file.raw.size / 1024 / 1024 < 10
      if (!isLt10M) {
        ElMessage.error('文件大小不能超过 10MB!')
        this.resetFile()
        return
      }

      // 检查文件内容是否为 BPMN 2.0
      const reader = new FileReader()
      reader.onload = (e) => {
        const content = e.target.result
        if (content.includes('bpmn')) {
          this.isFileValid = true
          ElMessage.success('文件验证通过')
        } else {
          ElMessage.error('文件内容不符合 BPMN 2.0 规范!')
          this.resetFile()
        }
      }
      reader.onerror = () => {
        ElMessage.error('文件读取失败!')
        this.resetFile()
      }
      reader.readAsText(file.raw)
    },
    resetFile() {
      this.selectedFile = null
      this.uploadForm.file = null
      this.fileList = []
      this.isFileValid = false
    },
    handleFileRemove() {
      this.resetFile()
    },
    beforeFileRemove() {
      return ElMessageBox.confirm('确定要移除该文件吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.resetFile()
        return true
      }).catch(() => {
        return false
      })
    }
  },
  created() {
    this.fetchList()
  },
  beforeUnmount() {
    if (this.bpmnViewer) {
      this.bpmnViewer.destroy()
    }
  }
}
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}
.card-list {
  margin-top: 20px;
}
.process-card {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.card-actions {
  display: flex;
  gap: 10px;
}
.card-content {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #606266;
}
.file-name {
  font-size: 14px;
  word-break: break-all;
}
.upload-demo {
  width: 100%;
}
.el-upload__tip {
  color: #909399;
  font-size: 12px;
  margin-top: 7px;
}
.preview-container {
  height: 600px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
.canvas {
  width: 100%;
  height: 100%;
}
</style> 